<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<input id="but1" class="but1" type="button" value="打印当前时间">
<button id="but2" class="but2">取消打印时间</button>

</body>
<script>
    let timer;
    let date;

    //开启计时
    function method() {
        date = new Date();
        console.log(date)
    }

    //使用class来获取
    let element = document.getElementsByClassName("but1");
    console.log(element[0]);
    element[0].onclick = function () {
        timer = window.setInterval("method()", 1000)
    }
    //设置新增事件依旧失败
    // element[0].addEventListener("onclick",function () {
    //     timer=window.setInterval("method()",1000);
    // });
    let elementById = document.getElementById("but1");
    console.log(elementById);
    // elementById.onclick=function () {
    //     timer=window.setInterval("method()",1000);
    // }
    //设置关闭
    let elementById1 = document.getElementById("but2");

    //使用匿名函数对点击事件操作 关闭计时
    elementById1.onclick = function () {
        clearInterval(timer)
    }
</script>
</html>